#import "WPViewControllerNewTreamentFirstEditeVC.h"
#import "HMDatePicker.h"
#import "WPCaseBtn.h"
#import "TZImagePickerController.h"
#import "WPMinePlaceholderTextView.h"
#import "WPMRModel.h"
#import "WPCustomTextAttachment.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "TZTestCell.h"
#import "WPVideoAndVoiceCell.h"
#import "WPAudioRecordVC.h"
#import "WPGetVideosFromPhotoVC.h"
#import "TZVideoPlayerController.h"
#import "WPTreamentProgressListModel.h"
#import "WPVideoOrAudioPlayController.h"
#import "SDTransparentPieProgressView.h"
#import "TZAssetModel.h"
#import "WPVideoOrAudioModel.h"

#define MARGIN 20.0
#define videoLength 5
@interface WPViewControllerNewTreamentFirstEditeVC ()<HMDatePickerDelegate,TZImagePickerControllerDelegate,UITextViewDelegate,UIActionSheetDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,WPGetVideosFromPhotoVCDelegate,WPAudioRecordVCDelegate>

@property(nonatomic,strong)UIView *topView;
@property(nonatomic,strong)UIView *bottomView;

@property(nonatomic,strong)WPCaseBtn *addPictureBtn;
@property(nonatomic,strong)WPCaseBtn *addVoiceBtn;
@property(nonatomic,strong)WPCaseBtn *addVideoBtn;

@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UIView *contentView;

@property(nonatomic,assign)CGFloat currentH;

@property(nonatomic,assign)CGRect oldFrame;
@property(nonatomic,assign)CGRect oldBottomViewFrame;

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSURL *urlPath;

@property(nonatomic,assign)CGFloat textMinHeight;

@property(nonatomic,strong)NSMutableArray *videoAndAudioArr;
@property(nonatomic,assign)NSInteger uploadingIndex;

/**
 富文本相关
 */
@property(nonatomic,assign)int index;

@end

@implementation WPViewControllerNewTreamentFirstEditeVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    [self.textView resignFirstResponder];
    [IQKeyboardManager sharedManager].enable = NO;
    
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    [self keyboardWillHide:nil];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.index = 1;
    self.uploadingIndex = -1;
    
    //注册通知,监听键盘弹出事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    self.view.backgroundColor  = [UIColor whiteColor];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_normal"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_highlight"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(backBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn sizeToFit];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacer.width = -8;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_left, nil];
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    //    saveBtn.backgroundColor = [UIColor orangeColor];
    [saveBtn setTitleColor:GloballightFontColor forState:UIControlStateHighlighted];
    [saveBtn addTarget:self action:@selector(saveBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    saveBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [saveBtn sizeToFit];
    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];
    
    UIBarButtonItem *nsr = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    nsr.width = -8;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer,btn_right, nil];
    
    self.title = self.model.name.length ? self.model.name : @"病例标题";
    
    [self setupUI];
}

-(void)setupUI
{
    [self topView];
    [self scrollView];
    [self textView];
    [self bottomView];
    [self collectionView];
}

-(UIView *)topView
{
    if (_topView == nil)
    {
        _topView = [UIView new];
        [self.view addSubview:_topView];
        
        [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(94);
            make.top.equalTo(self.view).offset(64);
        }];
        
        UIImageView *firstLine = [UIImageView lineImageView];
        UIImageView *secondLine = [UIImageView lineImageView];
        
        [_topView addSubview:firstLine];
        [_topView addSubview:secondLine];
        
        [firstLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(_topView);
            make.height.mas_equalTo(0.5);
            make.top.equalTo(_topView).offset(44);
        }];
        
        [secondLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(_topView);
            make.height.mas_equalTo(0.5);
        }];
        
        UILabel *timeLabel = [UILabel new];
        timeLabel.textColor = GLobalFontColor;
        timeLabel.text = @"症状时间:";
        timeLabel.font = [UIFont systemFontOfSize:15];
        [_topView addSubview:timeLabel];
        
        [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_topView).offset(10);
            make.top.equalTo(_topView).offset(15);
        }];
        
        _timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        _timeBtn.backgroundColor = [UIColor orangeColor];
        _timeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        
        if (self.model.descpTime.length)
        {
            [_timeBtn setTitle:self.model.descpTime forState:UIControlStateNormal];
            [_timeBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        }
        else
        {
            [_timeBtn setTitle:@"请输入症状时间" forState:UIControlStateNormal];
            [_timeBtn setTitleColor:RGB_COLOR(208, 208, 213) forState:UIControlStateNormal];
        }
        
        [_timeBtn addTarget:self action:@selector(timeBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [_topView addSubview:_timeBtn];
        
        [_timeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(timeLabel);
            make.left.equalTo(timeLabel.mas_right).offset(8);
        }];
        
        [self setupBtns];
    }
    return _topView;
}

-(void)setupBtns
{
    CGFloat width = SCREEN_WIDTH / 3.0;
    
    self.addPictureBtn = [WPCaseBtn buttonWithType:UIButtonTypeCustom];
    [self.addPictureBtn setTitle:@"添加图片" forState:UIControlStateNormal];
    [self.addPictureBtn setTitleColor:GloballightFontColor forState:UIControlStateHighlighted];
    [self.addPictureBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    self.addPictureBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.addPictureBtn setImage:[UIImage imageNamed:@"addPicture"] forState:UIControlStateNormal];
    [self.addPictureBtn setImage:[UIImage imageNamed:@"addPicture"] forState:UIControlStateHighlighted];
    [self.addPictureBtn addTarget:self action:@selector(addBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:self.addPictureBtn];
    
    [self.addPictureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.equalTo(_topView);
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(49);
    }];
    
    self.addVoiceBtn = [WPCaseBtn buttonWithType:UIButtonTypeCustom];
    //    self.addVoiceBtn.backgroundColor = [UIColor orangeColor];
    [self.addVoiceBtn setTitle:@"添加语音" forState:UIControlStateNormal];
    [self.addVoiceBtn setTitleColor:GloballightFontColor forState:UIControlStateHighlighted];
    [self.addVoiceBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    self.addVoiceBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.addVoiceBtn setImage:[UIImage imageNamed:@"voice"] forState:UIControlStateNormal];
    [self.addVoiceBtn setImage:[UIImage imageNamed:@"voice"] forState:UIControlStateHighlighted];
    [self.addVoiceBtn addTarget:self action:@selector(addBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:self.addVoiceBtn];
    
    [self.addVoiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.addPictureBtn);
        make.centerX.equalTo(_topView);
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(49);
    }];
    
    self.addVideoBtn = [WPCaseBtn buttonWithType:UIButtonTypeCustom];
    [self.addVideoBtn setTitleColor:GloballightFontColor forState:UIControlStateHighlighted];
    [self.addVideoBtn setTitle:@"添加视频" forState:UIControlStateNormal];
    [self.addVideoBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    self.addVideoBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.addVideoBtn setImage:[UIImage imageNamed:@"video"] forState:UIControlStateNormal];
    [self.addVideoBtn setImage:[UIImage imageNamed:@"video"] forState:UIControlStateHighlighted];
    [self.addVideoBtn addTarget:self action:@selector(addBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:self.addVideoBtn];
    
    [self.addVideoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(_topView);
        make.height.width.equalTo(self.addPictureBtn);
    }];
    
    UIImageView *firstLine = [UIImageView lineImageView];
    UIImageView *secondLine = [UIImageView lineImageView];
    
    [_topView addSubview:firstLine];
    [_topView addSubview:secondLine];
    
    [firstLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(0.5);
        make.left.equalTo(_topView).offset(width);
        make.height.mas_equalTo(34);
        make.centerY.equalTo(self.addPictureBtn);
    }];
    
    [secondLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.addPictureBtn);
        make.width.height.equalTo(firstLine);
        make.right.equalTo(_topView).offset(-width);
    }];
    
}

-(UIScrollView *)scrollView
{
    if (_scrollView == nil)
    {
        _scrollView = [UIScrollView new];
        _scrollView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_scrollView];
        
        [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(_topView.mas_bottom);
            
        }];
        
    }
    return _scrollView;
}

-(WPMinePlaceholderTextView *)textView
{
    if (_textView == nil)
    {
        _textView = [WPMinePlaceholderTextView new];
        _textView.placeholder = @"请详细填写该疾病的症状描述";
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.font = [UIFont systemFontOfSize:15];
        
        _textView.delegate = self;
        _textView.allowsEditingTextAttributes = YES;
        _textView.contentInset = UIEdgeInsetsMake(5, 5, 5, -5);
        
        CGFloat textViewH = (SCREEN_HEIGHT-158)/509.0*358;
        
        self.oldFrame = CGRectMake(0, 0, SCREEN_WIDTH, textViewH);
        
        [self.scrollView addSubview:_textView];
        
        _textView.frame = self.oldFrame;
        
        UIImageView *lineView = [UIImageView lineImageView];
        [self.scrollView addSubview:lineView];
        
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.scrollView);
            make.top.equalTo(_textView.mas_bottom);
            make.height.mas_equalTo(0.5);
        }];
    }
    return _textView;
}

-(UIView *)bottomView
{
    if (_bottomView == nil)
    {
        _bottomView = [UIView new];
        _bottomView.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_bottomView];
        
        CGFloat bottomView = (SCREEN_HEIGHT-158)/509.0*120;
        _bottomView.frame = CGRectMake(0, CGRectGetMaxY(self.textView.frame), SCREEN_WIDTH, bottomView);
        self.oldBottomViewFrame = _bottomView.frame;
        
        UIImageView *topLine = [UIImageView lineImageView];
        UIImageView *bottomLine = [UIImageView lineImageView];
        [_bottomView addSubview:topLine];
        [_bottomView addSubview:bottomLine];
        
        [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(_bottomView);
            make.height.mas_equalTo(0.5);
        }];
        
        [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.height.equalTo(topLine);
            make.bottom.equalTo(_bottomView);
        }];
    }
    return _bottomView;
}

-(UICollectionView *)collectionView
{
    if (_collectionView == nil)
    {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        
        [_collectionView registerClass:[WPVideoAndVoiceCell class] forCellWithReuseIdentifier:@"WPVideoAndVoiceCell"];
        [_collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
        [self.bottomView addSubview:_collectionView];
        
        CGFloat itemWidth = (SCREEN_WIDTH - 40)/3.0;
        CGFloat itemHeight = itemWidth;
        layout.itemSize = CGSizeMake(itemWidth, itemHeight);
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 5;
        
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.bottomView).offset(10);
            make.top.equalTo(self.bottomView).offset(15);
            make.bottom.equalTo(self.bottomView).offset(-15);
            make.right.equalTo(self.bottomView).offset(-10);
        }];
    }
    return _collectionView;
}

-(void)setModel:(WPMRModel *)model
{
    _model = model;
    
    self.title = self.model.name;
    [self.timeBtn setTitle:model.descpTime forState:UIControlStateNormal];
    
    NSArray *descp_List = model.treatmentProcess_list;
    
    for (WPVideoOrAudioModel *model in _model.processMultfile_list)
    {
        TZAssetModel *tzModel = [[TZAssetModel alloc] init];
        tzModel.urlPath = [NSURL URLWithString:model.fileUrl];
        tzModel.timeLength = model.multfileTime;
        if([model.type isEqualToString:@"video"])
        {
            tzModel.type = TZAssetModelMediaTypeVideo;
            tzModel.imageURL = model.imagUrl;
        }
        else
        {
            tzModel.type = TZAssetModelMediaTypeAudio;
        }
        tzModel.isUploaded = YES;
        tzModel.timeLength = model.multfileTime;
        [self.videoAndAudioArr addObject:tzModel];
    }
    
    self.textView.text = model.treamentProcessStr;
    
    //转换成富文本
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:@""];
    int k = 0;
    
    if ([descp_List[0] hasPrefix:@"http://"])
    {
        [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
    }
    
    for(NSString *str in descp_List)
    {
        k++;
        
        if ([str hasPrefix:@"http://"])
        {
            NSString *url = str;
            UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:url];
            
            if (image)
            {
                WPCustomTextAttachment *attach = [[WPCustomTextAttachment alloc] init];
                attach.url = url;
                attach.image = image;
                
                CGFloat imageRate = image.size.width / image.size.height;
                attach.bounds = CGRectMake(0, MARGIN*0.5, SCREEN_WIDTH-MARGIN, (SCREEN_WIDTH-MARGIN) / imageRate);
                NSAttributedString *imageAttr = [NSAttributedString attributedStringWithAttachment:attach];
                
                if (!attStr)
                {
                    attStr = [[NSMutableAttributedString alloc] initWithAttributedString:imageAttr];
                }
                else
                {
                    [attStr appendAttributedString:imageAttr];
                }
                
                //如果下一张哈还是图片就换行,否则不换行
                if (k <= (descp_List.count-1))
                {
                    if ([descp_List[k] hasPrefix:@"http://"])
                    {
                        //添加换行符
                        [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
                        //添加换行符
                        [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
                    }
                    else
                    {
                        //添加换行符
                        [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
                    }
                }
                else
                {
                    //添加换行符
                    [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
                }
                
            }
            else
            {
                NSAttributedString *failedStr = [[NSAttributedString alloc] initWithString:@"[图片加载失败]"];
                if (!attStr)
                {
                    attStr = [[NSMutableAttributedString alloc] initWithAttributedString:failedStr];
                }
                else
                {
                    [attStr appendAttributedString:failedStr];
                }
            }
            
        }
        else
        {
            if (!attStr)
            {
                attStr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
            }
            else
            {
                NSAttributedString *as = [[NSAttributedString alloc] initWithString:str];
                [attStr appendAttributedString:as];
            }
            
            //wenben添加换行符
            [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
        }
        
    }
    
    [attStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} range:NSMakeRange(0, attStr.length)];
    
    self.textView.attributedText = attStr;
    
    if (attStr.length)
    {
        self.textView.placeholderLabel.hidden = YES;
    }
    else
    {
        self.textView.placeholderLabel.hidden = NO;
    }
}

#pragma mark - collectionView的代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.videoAndAudioArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WPVideoAndVoiceCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WPVideoAndVoiceCell" forIndexPath:indexPath];
    cell.model = self.videoAndAudioArr[indexPath.item];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == self.uploadingIndex)
    {
        return ;
    }
    
    TZAssetModel *model = self.videoAndAudioArr[indexPath.item];
    if (model.isUploaded)
    {
        //上传成功才可以观看
        WPVideoOrAudioPlayController *avpc = [WPVideoOrAudioPlayController new];
        avpc.recordId = self.model.id;
        avpc.rank = self.rank;
        avpc.videoAndAudioArr = [NSMutableArray arrayWithObject:model];
        avpc.selectedIndex = indexPath.item;
        avpc.deleteBlock = ^{
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:self.model.processMultfile_list];
            [arr removeObjectAtIndex:indexPath.item];
            self.model.processMultfile_list = arr;
            
            [self.videoAndAudioArr removeObject:model];
            //刷新collectionView
            [self.collectionView reloadData];
        };
        [self presentViewController:avpc animated:YES completion:nil];
    }
    else
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"视频上传失败,是否继续上传?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *againUpload = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            //重新上传
            [self uploadVideoOrAudioToServeWith:model index:indexPath.item];
            
        }];
        [alertController addAction:cancel];
        [alertController addAction:againUpload];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - TZImagePickerController

- (void)pushImagePickerControllerWithPickingImage:(BOOL)allowPickingImage pickingVideo:(BOOL)allowPickingvideo
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    
    // 1.如果你需要将拍照按钮放在外面，不要传这个参数
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = allowPickingvideo;
    imagePickerVc.allowPickingImage = allowPickingImage;
    imagePickerVc.allowPickingOriginalPhoto = allowPickingImage;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = NO;
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

// 键盘弹出时调用方法
-(void)keyboardDidShow:(NSNotification *)notification
{
    self.textView.scrollEnabled = YES;
    
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    //    CGFloat height = keyboardRect.size.height;
    
    
    CGRect tfRect = [self.textView.superview convertRect:self.oldFrame toView:[UIApplication sharedApplication].keyWindow];
    
    CGFloat keyBoardMinY = CGRectGetMinY(keyboardRect);
    CGFloat textViewMaxY = CGRectGetMaxY(tfRect);
    
    //    NSLog(@"%f %f", keyBoardMinY, textViewMaxY);
    
    CGFloat moveDistance = textViewMaxY - keyBoardMinY;
    
    // 获取压缩后的高度
    CGFloat h = self.oldFrame.size.height - moveDistance;
    self.textMinHeight = h;
    // 定义一个新的矩形，具有压缩后的高度
    CGRect rect = CGRectMake(self.oldFrame.origin.x, self.oldFrame.origin.y, self.oldFrame.size.width, h);
    
    // 赋值给 textView
    self.textView.frame = rect;
}

//当键盘出现或改变时调用
-(void)keyboardWillHide:(NSNotification *)aNotification
{
    self.textView.scrollEnabled = NO;
    
    CGRect bounds = self.textView.bounds;
    
    // 计算 text view 的高度
    CGSize maxSize = CGSizeMake(bounds.size.width, CGFLOAT_MAX);
    CGSize newSize = [self.textView sizeThatFits:maxSize];
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    CGFloat textViewH = (newSize.height > self.oldFrame.size.height?newSize.height:self.oldFrame.size.height);
    CGFloat bottomH = [self bottomViewHeighWith:(int)self.videoAndAudioArr.count];
    
    if(!bottomH)
    {
        self.bottomView.hidden = YES;
    }
    else
    {
        self.bottomView.hidden = NO;
    }
    
    self.scrollView.contentSize = CGSizeMake(self.oldFrame.size.width, textViewH+bottomH+30);
    [UIView animateWithDuration:duration animations:^{
        
        self.textView.frame = CGRectMake(self.oldFrame.origin.x, self.oldFrame.origin.y, self.oldFrame.size.width, textViewH);
        self.bottomView.frame = CGRectMake(0, CGRectGetMaxY(self.textView.frame), self.oldFrame.size.width, bottomH);
    }];
}

-(CGFloat)bottomViewHeighWith:(int)count
{
    if (!count)
    {
        return 0.0;
    }
    else
    {
        CGFloat itemH = (SCREEN_WIDTH - 40)/3.0;
        int row = (count-1)/3 + 1;
        return row*itemH + (row -1)*10 +30;
    }
}

#pragma mark - UITextView的代理方法
//- (void)textViewDidChangeSelection:(UITextView *)textView
//{
//    NSInteger location = textView.selectedRange.location;
//    NSAttributedString *att = textView.attributedText;
//    
//    if(location == att.length)
//    {
//        return ;
//    }
//    
//    //遍历
//    [att enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, att.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
//        
//        if (range.location == location)
//        {
//            //检查类型是否是自定义NSTextAttachment类
//            if (value && [value isKindOfClass:[WPCustomTextAttachment class]])
//            {
//                textView.selectedRange = NSMakeRange(location-1, 0);
//            }
//        }
//    }];
//}

#pragma mark - 按钮响应事件方法
-(void)backBtnDidClick
{
    [self.view endEditing:YES];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)saveBtnDidClick:(UIButton *)btn
{
    
    if (!self.textView.attributedText.length)
    {
        [self showInfoStatus:@"内容不能为空"];
        return ;
    }
    
    [self showWithStatus:@"正在保存"];
    //保存治疗说明
    NSString *url = @"record/editProcessDescp.do";
    // 1. 发送带有图片标志的纯文本到服务器
    NSString *textString = [self textStringWithSymbol:@"[图片]" attributeString:self.textView.attributedText];
    
    //去掉多余的图片前的换行符
    textString = [self deleteNewlineWith:textString];
    
    if (!self.isVisit)
    {
        WPEditeModel *editeModel = [WPEditeModel new];
        editeModel.recordId = self.model.id;
        editeModel.rank = 1;
        
        if (![self.timeBtn.titleLabel.text isEqualToString:@"请输入症状时间"])
        {
            editeModel.writeTime = self.timeBtn.titleLabel.text;
        }
        else
        {
            editeModel.writeTime = @"";
        }
        
        editeModel.descp = textString;
        
        NSString *JSONStr = [editeModel yy_modelToJSONString];
        NSDictionary *dict = @{@"json":JSONStr};
        
        if (self.photos.count)
        {
            for (NSNumber *index in self.imageNameArr)
            {
                int i = index.intValue-1;
                if (i >= 0)
                {
                    UIImage *image = self.photos[i];
                    NSString *totalPath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%lu.jpg",(unsigned long)i+1]];
                    
                    NSData *data = UIImageJPEGRepresentation(image, 0.6);
                    [data writeToFile:totalPath atomically:NO];
                    
                    NSURL *imageURL = [NSURL fileURLWithPath:totalPath];
                    
                    [self.pathArr addObject:imageURL];
                }
            }
        }
        
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            for (NSURL *imageURL in self.pathArr)
            {
                [formData appendPartWithFileURL:imageURL name:@"file" error:nil];
            }
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self dismiss];
            
            if([responseObject[@"result"] isEqualToString:@"success"])
            {
                [self showSuccessInfoWithStatus:@"保存成功"];
                
                NSDictionary *dict = responseObject[@"detail"];
                NSString *recordDescp = dict[@"descp"];
                NSArray *recordDescp_list = dict[@"descp_list"];
                NSString *writeTime = dict[@"writeTime"];
                self.model.treatmentProcess = recordDescp;
                self.model.treatmentProcess_list = recordDescp_list;
                self.model.descpTime = writeTime;
                
                //刷新
                if (self.reloadBlock)
                {
                    self.reloadBlock();
                }
            }
            else
            {
                //            考虑到账号过期的情况
                if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                {
                    //                账号过期
                    [self illegalLoginWithSuccessBlock:^{
                        //点击确定后的回调
                        
                        WPMineLoginVC *vc = [WPMineLoginVC new];
                        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
                    }];
                }
                else
                {
                    [self showErrorInfoWithStatus:responseObject[@"detail"]];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [self dismiss];
            [self showErrorInfoWithStatus:@"网络错误"];
        }];
//        NSLog(@"*******%@",textString);
    }
    else
    {
        WPTreamentProgressListModel *visiteModel = nil;
        if (self.model.processDescp_list.count)
        {
            //不是第一次
            visiteModel = self.model.processDescp_list[self.visitIndex];
        }
        else
        {
            //第一次
            visiteModel = [WPTreamentProgressListModel new];
            
            NSMutableArray *processDescp_list = [NSMutableArray array];
            [processDescp_list addObject:visiteModel];
            self.model.processDescp_list = processDescp_list;
        }
        
        //治疗过程的复诊的保存
        WPEditeModel *editeModel = [WPEditeModel new];
        editeModel.id = visiteModel.id;
        editeModel.recordId = self.model.id;
        editeModel.rank = self.visitIndex + 2;
        editeModel.writeTime = self.timeBtn.titleLabel.text;
        editeModel.descp = textString;
        
        NSString *JSONStr = [editeModel yy_modelToJSONString];
        NSDictionary *dict = @{@"json":JSONStr};
        if (self.photos.count)
        {
            for (NSNumber *index in self.imageNameArr)
            {
                int i = index.intValue-1;
                if (i >= 0)
                {
                    UIImage *image = self.photos[i];
                    NSString *totalPath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%lu.jpg",(unsigned long)i+1]];
                    
                    NSData *data = UIImageJPEGRepresentation(image, 0.6);
                    [data writeToFile:totalPath atomically:NO];
                    
                    NSURL *imageURL = [NSURL fileURLWithPath:totalPath];
                    
                    [self.pathArr addObject:imageURL];
                }
            }
        }
        
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            for (NSURL *imageURL in self.pathArr)
            {
                [formData appendPartWithFileURL:imageURL name:@"file" error:nil];
            }
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if([responseObject[@"result"] isEqualToString:@"success"])
            {
                NSDictionary *dict = responseObject[@"detail"];
                visiteModel.descp = dict[@"descp"];
                visiteModel.descp_list = dict[@"descp_list"];
                visiteModel.writeTime = dict[@"writeTime"];
                visiteModel.rank = [dict[@"rank"] intValue];
                visiteModel.recordId = [dict[@"recordId"] integerValue];
                visiteModel.id = [dict[@"id"] intValue];
                
                [self showSuccessInfoWithStatus:@"保存成功"];
                
                //刷新
                if (self.reloadBlock)
                {
                    self.reloadBlock();
                }
            }
            else
            {
                //            考虑到账号过期的情况
                if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                {
                    //                账号过期
                    [self illegalLoginWithSuccessBlock:^{
                        
                        //点击确定后的回调
                        
                    }];
                }
                else
                {
                    [self showErrorInfoWithStatus:responseObject[@"detail"]];
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [self showErrorInfoWithStatus:@"网络错误"];
        }];
    }
}

#pragma mark - 将富文本转换为带有图片标志的纯文本
/** 将富文本转换为带有图片标志的纯文本*/
- (NSString *)textStringWithSymbol:(NSString *)symbol attributeString:(NSAttributedString *)attributeString{
    
    NSString *string = attributeString.string;
    
    string = [self stringDeleteString:@"\n" frontString:symbol inString:string];
    //最终纯文本
    NSMutableString *textString = [NSMutableString stringWithString:string];
    //替换下标的偏移量
    __block NSUInteger base = 0;
    
    //遍历
    [attributeString enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, attributeString.length)
                                options:0
                             usingBlock:^(id value, NSRange range, BOOL *stop) {
                                 //检查类型是否是自定义NSTextAttachment类
                                 if (value && [value isKindOfClass:[WPCustomTextAttachment class]]) {
                                     WPCustomTextAttachment *att = (WPCustomTextAttachment *)value;
                                     
                                     if(att.index > 0)
                                     {
                                         [self.imageNameArr addObject:@(att.index)];
                                     }
                                     
                                     NSString *replaceStr = [NSString stringWithFormat:@"[%@]",att.url];
                                     //替换
                                     [textString replaceCharactersInRange:NSMakeRange(range.location + base, range.length) withString:replaceStr];
                                     //增加偏移量
                                     base += (replaceStr.length - 1);
                                 }
                             }];
    
    return textString;
}

/** 删除字符串*/
- (NSString *)stringDeleteString:(NSString *)deleteString frontString:(NSString *)frontString inString:(NSString *)inString{
    
    NSArray *ranges = [self rangeOfSymbolString:frontString inString:inString];
    NSMutableString *mutableString = [inString mutableCopy];
    NSUInteger base = 0;
    for (NSString *rangeString in ranges) {
        NSRange range = NSRangeFromString(rangeString);
        [mutableString deleteCharactersInRange:NSMakeRange(range.location - deleteString.length + base, deleteString.length)];
        base -= deleteString.length;
    }
    return [mutableString copy];
}

/** 统计文本中所有图片资源标志的range*/
- (NSArray *)rangeOfSymbolString:(NSString *)symbol inString:(NSString *)string {
    
    NSMutableArray *rangeArray = [NSMutableArray array];
    NSString *string1 = [string stringByAppendingString:symbol];
    NSString *temp;
    for (int i = 0; i < string.length; i ++) {
        
        temp = [string1 substringWithRange:NSMakeRange(i, symbol.length)];
        if ([temp isEqualToString:symbol]) {
            NSRange range = {i, symbol.length};
            [rangeArray addObject:NSStringFromRange(range)];
        }
    }
    return rangeArray;
}

//删除[]前的换行符
-(NSString *)deleteNewlineWith:(NSString *)str
{
    NSString *mutableStr = [NSString stringWithFormat:@"%@",str];
    // 表情的规则
    NSString *emotionPattern = @"\\[.*\\]";
    // 使用系统的正则类来遍历
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:emotionPattern options:0 error:nil];
    
    // 2.测试字符串
    NSArray *results = [regex matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    // 3.遍历结果
    for (NSTextCheckingResult *result in results)
    {
        //删除图片前的换行
        NSString *subString = [NSString stringWithFormat:@"\n%@",[str substringWithRange:result.range]];
        mutableStr = [mutableStr stringByReplacingOccurrencesOfString:subString withString:[str substringWithRange:result.range]];
        
        //删除图片后的换行
        subString = [NSString stringWithFormat:@"%@\n",[str substringWithRange:result.range]];
        mutableStr = [mutableStr stringByReplacingOccurrencesOfString:subString withString:[str substringWithRange:result.range]];
    }
    return mutableStr;
}

-(void)addBtnDidClick:(UIButton *)btn
{
    [self.view endEditing:YES];
    
    if (btn == self.addPictureBtn)
    {
        //添加图片
        [self pushImagePickerControllerWithPickingImage:YES pickingVideo:NO];
    }
    else if (btn == self.addVoiceBtn)
    {
        [self.textView resignFirstResponder];
        //添加语音
        WPAudioRecordVC *vc = [WPAudioRecordVC new];
        vc.delegate = self;
        [self presentViewController:vc animated:YES completion:nil];
    }
    else if(btn == self.addVideoBtn)
    {
        //添加视频
        
        WPGetVideosFromPhotoVC *vfpc = [WPGetVideosFromPhotoVC new];
        UINavigationController *vc = [[UINavigationController alloc] initWithRootViewController:vfpc];
        vfpc.delegate = self;
        [self presentViewController:vc animated:YES completion:nil];
    }
}



-(void)timeBtnDidClick:(UIButton *)btn
{
    [self.view endEditing:YES];
    // 创建日期选择器
    HMDatePicker *pickerView = [HMDatePicker datePicker];
    // 设置代理
    pickerView.delegate = self;
    // 设置datePicker当前显示的时间
    pickerView.currentDate = [NSDate date];
    // 显示
    [pickerView show];
}

#pragma mark - WPAudioRecordVCDelegate
-(void)WPAudioRecordVCDoneWith:(WPAudioRecordVC *)vc audio:(TZAssetModel *)model
{
    [self.videoAndAudioArr addObject:model];
    
    [self updateVideosAndAudioFrame];
    [self.collectionView reloadData];
    
    //让scrollView滚到底部
    CGFloat offsetY = self.scrollView.contentSize.height - self.scrollView.bounds.size.height;
    [self.scrollView setContentOffset:CGPointMake(0, offsetY) animated:YES];
    
    NSInteger index = [self.videoAndAudioArr indexOfObject:model];
    
    [self uploadVideoOrAudioToServeWith:model index:index];
}

#pragma mark - WPGetVideosFromPhotoVCDelegate
-(void)WPGetVideosFromPhotoVCDoneWith:(WPGetVideosFromPhotoVC *)vc videos:(NSArray *)videos
{
    [self.videoAndAudioArr addObjectsFromArray:videos];
    
    [self updateVideosAndAudioFrame];
    
    [self.collectionView reloadData];
    
    CGFloat offsetY = self.scrollView.contentSize.height - self.scrollView.bounds.size.height;
    [self.scrollView setContentOffset:CGPointMake(0, offsetY) animated:YES];
    
    TZAssetModel *model = videos[0];
    NSInteger index = [self.videoAndAudioArr indexOfObject:model];
    
    [self uploadVideoOrAudioToServeWith:model index:index];
}

-(void)WPGetVideosFromCameraWith:(WPGetVideosFromPhotoVC *)vc videoModel:(TZAssetModel *)model
{
    [self.videoAndAudioArr addObject:model];
    
    [self updateVideosAndAudioFrame];
    
    [self.collectionView reloadData];
    
    CGFloat offsetY = self.scrollView.contentSize.height - self.scrollView.bounds.size.height;
    [self.scrollView setContentOffset:CGPointMake(0, offsetY) animated:YES];
    
    NSInteger index = [self.videoAndAudioArr indexOfObject:model];
    
    [self uploadVideoOrAudioToServeWith:model index:index];
}

-(void)uploadVideoOrAudioToServeWith:(TZAssetModel *)model index:(NSInteger)index
{
    self.uploadingIndex = index;
    
    //上传服务器
    NSString *url = @"record/uploadMultfile.do";
    
    NSDictionary *dict = @{@"recordId":@(self.model.id),@"rank":@(self.rank)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileURL:model.urlPath name:@"file" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        CGFloat progress = ((CGFloat)uploadProgress.completedUnitCount)/uploadProgress.totalUnitCount;
        WPVideoAndVoiceCell *cell = (WPVideoAndVoiceCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            cell.progressView.progress = progress;
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = responseObject[@"detail"];
        if ([responseObject[@"result"] isEqualToString:@"success"])
        {
            WPVideoAndVoiceCell *cell = (WPVideoAndVoiceCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                cell.failedImageView.hidden = YES;
            });
            
            model.isUploaded = YES;
            [self showResultOfVideoOrAudioUploadWith:YES];
            
            NSMutableArray *arr = [NSMutableArray array];
            
            NSArray *multFile_list = dict[@"multFile_list"];
            for (NSDictionary *videoOrAudioDict in multFile_list)
            {
                WPVideoOrAudioModel *model = [WPVideoOrAudioModel yy_modelWithDictionary:videoOrAudioDict];
                [arr addObject:model];
            }
            
            self.model.processMultfile_list = arr;
        }
        else
        {
            WPVideoAndVoiceCell *cell = (WPVideoAndVoiceCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                cell.failedImageView.hidden = NO;
            });
            
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                [self illegalLoginWithSuccessBlock:^{
                    
                    //点击确定后的回调
                }];
            }
            else
            {
                [self showResultOfVideoOrAudioUploadWith:NO];
            }
            
        }
        self.uploadingIndex = -1;
        
//        WPLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        WPVideoAndVoiceCell *cell = (WPVideoAndVoiceCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            cell.failedImageView.hidden = NO;
        });
        [self showErrorInfoWithStatus:@"网络错误"];
        self.uploadingIndex = -1;
        
//        WPLog(@"%@",error);
    }];
}

-(void)showResultOfVideoOrAudioUploadWith:(BOOL)isSuccess
{
    UILabel *label = [UILabel new];
    label.backgroundColor = RGB_SAME(51);
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = [UIColor whiteColor];
    label.layer.cornerRadius = 4;
    label.layer.masksToBounds = YES;
    label.alpha = 1.0;
    label.textAlignment = NSTextAlignmentCenter;
    
    if (isSuccess)
    {
        label.text = @"上传成功";
    }
    else
    {
        label.text = @"上传失败";
    }
    
    [self.view addSubview:label];
    CGSize size = [label.text sizeWithMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:15];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(SCREEN_HEIGHT*0.25);
        make.width.mas_equalTo(size.width + 40);
        make.height.mas_equalTo(size.height + 20);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:1 animations:^{
            
            label.alpha = 0.0;
        } completion:^(BOOL finished) {
            
            [label removeFromSuperview];
        }];
        
    });
    
}

-(void)updateVideosAndAudioFrame
{
    self.textView.scrollEnabled = NO;
    
    CGRect bounds = self.textView.bounds;
    
    // 计算 text view 的高度
    CGSize maxSize = CGSizeMake(bounds.size.width, CGFLOAT_MAX);
    CGSize newSize = [self.textView sizeThatFits:maxSize];
    
    
    CGFloat textViewH = (newSize.height > self.oldFrame.size.height?newSize.height:self.oldFrame.size.height);
    CGFloat bottomH = [self bottomViewHeighWith:(int)self.videoAndAudioArr.count];
    
    self.scrollView.contentSize = CGSizeMake(self.oldFrame.size.width, textViewH+bottomH+30);
    
    self.textView.frame = CGRectMake(self.oldFrame.origin.x, self.oldFrame.origin.y, self.oldFrame.size.width, textViewH);
    self.bottomView.frame = CGRectMake(0, CGRectGetMaxY(self.textView.frame), self.oldFrame.size.width, bottomH);
}

#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    //这里可以拿到选择的图片
    NSUInteger location = self.textView.selectedRange.location;
    
    NSMutableAttributedString *mutableAttr = [self.textView.attributedText mutableCopy];
    // 1. 保存图片与图片的location
    for (UIImage *image in photos)
    {
        [self.photos addObject:image];
        
        [mutableAttr insertAttributedString:[[NSAttributedString alloc] initWithString:@"\n"] atIndex:location];
        location++;
        
        // 2. 将图片插入到富文本中
        WPCustomTextAttachment *attach = [[WPCustomTextAttachment alloc] init];
        attach.image = image;
        attach.url = [NSString stringWithFormat:@"%zd.jpg",self.index];
        attach.index = self.index;
        
        CGFloat imageRate = image.size.width / image.size.height;
        attach.bounds = CGRectMake(0, MARGIN*0.5, self.textView.frame.size.width - MARGIN, (self.textView.frame.size.width - MARGIN) / imageRate);
        NSAttributedString *imageAttr = [NSAttributedString attributedStringWithAttachment:attach];
        [mutableAttr insertAttributedString:imageAttr atIndex:location];
        
        location++;
        self.index++;
    }
    
    [mutableAttr insertAttributedString:[[NSAttributedString alloc] initWithString:@"\n"] atIndex:location];
    location++;
    
    self.textView.attributedText = mutableAttr;
    self.textView.font = [UIFont systemFontOfSize:15];
    self.textView.selectedRange = NSMakeRange(location, 0);
    
    [self.textView becomeFirstResponder];
}

-(void)compressedVideoOtherMethodWithURL:(NSURL *)url compressionType:(NSString *)compressionType compressionResultPath:(void(^)(BOOL isSaveSuccess, CGFloat totalSize, CGFloat outPutSize))resultPathBlock {
    
    NSString *resultPath;
    
    NSData *data = [NSData dataWithContentsOfURL:url];
    CGFloat totalSize = (float)data.length / 1024 / 1024;
    
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:compressionType];
    
    //保存至沙盒路径
    NSString *pathDocuments = [documentPath stringByAppendingPathComponent:@"WBWYVideos"];
    
    BOOL isDir = NO;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:pathDocuments isDirectory:&isDir];
    if (!isExist || (isExist && !isDir))
    {
        NSError *error = nil;
        [[NSFileManager defaultManager] createDirectoryAtPath:pathDocuments withIntermediateDirectories:YES attributes:nil error:&error];
        if (error == nil)
        {
            NSLog(@"目录创建成功");
        } else
        {
            NSLog(@"目录创建失败");
        }
    }
    
    // 用时间, 给文件重新命名, 防止视频存储覆盖
    resultPath = [pathDocuments stringByAppendingPathComponent:[NSString stringWithFormat:@"outputJFVideo-%@.mp4", [[WPDateFormatterManager sharedManager] stringFromDateWithDate:[NSDate date] format:@"yyyy-MM-dd-HH:mm:ss"]]];
    
    exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
    
    exportSession.outputFileType = AVFileTypeMPEG4;
    
    exportSession.shouldOptimizeForNetworkUse = YES;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     
     {
         if (exportSession.status == AVAssetExportSessionStatusCompleted)
         {
             
             NSData *data = [NSData dataWithContentsOfFile:resultPath];
             
             float memorySize = (float)data.length / 1024 / 1024;
             
             resultPathBlock(YES,totalSize,memorySize);
             
         } else
         {
             
             resultPathBlock(NO,0.0,0.0);
         }
         
     }];
}


- (void)datePickerDidValueChanged:(HMDatePicker *)datePicker
{
    NSDate *date = datePicker.datePicker.date;
    NSString *dateStr = [[WPDateFormatterManager sharedManager] stringFromDateWithDate:date format:@"yyyy-MM-dd"];
    
    [self.timeBtn setTitle:dateStr forState:UIControlStateNormal];
    [self.timeBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
}

- (NSMutableArray *)photos{
    if (!_photos) {
        _photos = [NSMutableArray array];
    }
    return _photos;
}

-(NSMutableArray *)videoAndAudioArr
{
    if (_videoAndAudioArr == nil)
    {
        _videoAndAudioArr = [NSMutableArray array];
    }
    return _videoAndAudioArr;
}

-(NSMutableArray *)imageNameArr
{
    if (_imageNameArr == nil)
    {
        _imageNameArr = [NSMutableArray array];
    }
    return _imageNameArr;
}

-(NSMutableArray *)pathArr
{
    if (_pathArr == nil)
    {
        _pathArr = [NSMutableArray array];
    }
    return _pathArr;
}

-(void)dealloc
{
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
//    WPLog(@"治疗说明编辑控制器死了");
}
@end
